import Vue from "vue";
import VueRouter from "vue-router";
import MyIndex from "../views/MyIndex.vue";
import Detail from "../views/Detail.vue";
import Order from "../views/OrderForm.vue";
import { Toast } from "vant";
Vue.use(Toast);
Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect: "/index",
  },
  {
    path: "/index",
    name: "index",
    component: () => import("@/components/index/index.vue"),
  },
  {
    path: "/search",
    name: "search",
    component: () => import("@/components/search/Search.vue"),
  },
  {
    path: "/login",
    component: () => import("@/views/Login.vue"),
  },
  {
    path: "/register",
    component: () => import("@/views/Register.vue"),
  },
  {
    path: "/list",
    name: "list",
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/ListView.vue"),
  },
  {
    path: "/ucenter",
    name: "ucenter",
    component: MyIndex,
  },
  {
    path: "/detail",
    component: Detail,
  },
  {
    path: "/car",
    name: "car",
    component: () => import("@/views/car"),
  },
  {
    path: "/order",
    component: Order,
    meta: {
      isLogin: true,
    },
  },
  {
    path: "/hhhhhh",
    component: () => import("@/views/Hhhhh.vue"),
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});
const originalPush = VueRouter.prototype.push;

VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject);

  return originalPush.call(this, location).catch((err) => err);
};

export default router;
router.beforeEach((to, from, next) => {
  if (to.meta.isLogin) {
    if (localStorage.getItem("token")) {
      next();
    } else {
      Toast.fail("请登录");
      next("/login");
    }
  } else {
    next();
  }
  next();
});
